#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

from PySide import QtGui
from tder_maya import undoPmel
import pymel.core as pmel
import random

class ReplaceDialog(QtGui.QDialog):
    def __init__(self, parent=QtGui.QApplication.activeWindow()):
        super(ReplaceDialog, self).__init__(parent)
        from .pyuic.replace_form import Ui_replaceForm
        self._ui = Ui_replaceForm()
        self._ui.setupUi(self)
        self._ui.detailWidget.hide()
        self._ui.addRepObjBtn.clicked.connect(self.on_add_obj_btn_clicked)
        self._ui.delRepObjBtn.clicked.connect(self.on_del_obj_btn_clicked)
        self._ui.repRunBtn.clicked.connect(self.on_rep_run_btn_clicked)

    def message_dialog(self, text):
        messageBox = QtGui.QMessageBox(self)
        messageBox.setWindowTitle(u'提示')
        messageBox.addButton('    ok    ', QtGui.QMessageBox.ActionRole)
        messageBox.setText(text)
        messageBox.exec_()

    def on_add_obj_btn_clicked(self):
        selObjList = [obj.name() for obj in pmel.ls(sl=1)]
        if not selObjList:
            return
        itemList = self.get_obj_list_widget_items()
        if itemList:
            for obj in selObjList:
                if obj not in itemList:
                    self._ui.repObjListWidget.addItem(obj)
        else:
            self._ui.repObjListWidget.addItems(selObjList)

    def on_del_obj_btn_clicked(self):
        currentRow = self._ui.repObjListWidget.currentRow()
        self._ui.repObjListWidget.takeItem(currentRow)

    def get_obj_list_widget_items(self):
        count = self._ui.repObjListWidget.count()
        itemList = []
        if not count:
            return
        for i in range(count):
            item = self._ui.repObjListWidget.item(i)
            itemList.append(item.text())
        return itemList

    @undoPmel
    def on_rep_run_btn_clicked(self):
        targetObjList = self.get_obj_list_widget_items()
        if not targetObjList:
            return
        selObjList = pmel.ls(sl=1)
        if not selObjList:
            return
        for obj in selObjList:
            targetObj = random.choice(targetObjList)
            copyObj = pmel.duplicate(pmel.PyNode(targetObj), ilf=1)[0]
            copyObj.translate.set(obj.translate.get())
            copyObj.rotate.set(obj.rotate.get())
            copyObj.scale.set(obj.scale.get())
            pmel.delete(obj)

